import { _HttpClient, SettingsService } from '@delon/theme';
import { AfterViewInit, Component, Inject, OnDestroy, OnInit, Optional } from '@angular/core';
import { Router } from '@angular/router';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { NzMessageService, NzModalService } from 'ng-zorro-antd';
import { DA_SERVICE_TOKEN, ITokenService, SocialService } from '@delon/auth';
import { ReuseTabService } from '@delon/abc';
import { StartupService } from '@core';
import { Md5 } from 'ts-md5';
import { CacheService } from '@delon/cache';

@Component({
  selector: 'passport-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.less'],
  providers: [SocialService],
})
export class UserLoginComponent implements OnDestroy, OnInit, AfterViewInit {
  form: FormGroup;
  error = '';
  type = 0;

  autopwd = false;

  constructor(
    private fb: FormBuilder,
    private modalSrv: NzModalService,
    private router: Router,
    private settingsService: SettingsService,
    private socialService: SocialService,
    private settingService: SettingsService,
    @Optional()
    @Inject(ReuseTabService)
    private reuseTabService: ReuseTabService,
    @Inject(DA_SERVICE_TOKEN) private tokenService: ITokenService,
    private startupSrv: StartupService,
    public http: _HttpClient,
    public msg: NzMessageService,
    private cacheSer: CacheService
  ) {

  }

  // #region fields

  get userName() {
    return this.form.controls.userName;
  }

  get password() {
    return this.form.controls.password;
  }

  get mobile() {
    return this.form.controls.mobile;
  }

  get captcha() {
    return this.form.controls.captcha;
  }

  get rememberme() {
    return this.form.controls.remember;
  }

  count = 0;
  interval$: any;

  getCaptcha() {
    if (this.mobile.invalid) {
      this.mobile.markAsDirty({onlySelf: true});
      this.mobile.updateValueAndValidity({onlySelf: true});
      return;
    }
    this.count = 59;
    this.interval$ = setInterval(() => {
      this.count -= 1;
      if (this.count <= 0) clearInterval(this.interval$);
    }, 1000);
  }

  // #endregion

  submit() {
    this.error = '';
    if (this.type === 0) {
      this.userName.markAsDirty();
      this.userName.updateValueAndValidity();
      this.password.markAsDirty();
      this.password.updateValueAndValidity();
      if (this.userName.invalid || this.password.invalid) return;
    } else {
      this.mobile.markAsDirty();
      this.mobile.updateValueAndValidity();
      this.captcha.markAsDirty();
      this.captcha.updateValueAndValidity();
      if (this.mobile.invalid || this.captcha.invalid) return;
    }

    // 默认配置中对所有HTTP请求都会强制 [校验](https://ng-alain.com/auth/getting-started) 用户 Token
    // 然一般来说登录请求不需要校验，因此可以在请求URL加上：`/login?_allow_anonymous=true` 表示不触发用户 Token 校验
    this.http
      .post('security/auth/login?_allow_anonymous=true', {
        type: this.type,
        username: this.userName.value,
        password: this.autopwd ? this.password.value : Md5.hashStr(this.password.value),
      })
      .subscribe((res: any) => {
        // 清空路由复用信息
        this.reuseTabService.clear();
        if (!res['avatar']) {
          res['avatar'] = './assets/tmp/img/avatar.jpg';
        }
        // 用户信息：包括姓名、头像、邮箱地址
        //this.settingService.setUser(res.data);
        this.cacheSer.set('$remember', {
          username: this.userName.value,
          password: this.rememberme.value ? Md5.hashStr(this.password.value) : '',
          rememberme: this.rememberme.value
        })

        // 设置用户Token信息
        this.tokenService.set(res.data);
        const user = {
          "name": res.data.name,
          "avatar": "./assets/tmp/img/avatar.jpg",
          "email": "906368691@qq.com"
        }
        this.settingService.setUser(user);
        // 重新获取 StartupService 内容，我们始终认为应用信息一般都会受当前用户授权范围而影响
        this.startupSrv.load().then(() => {
          let url = this.tokenService.referrer.url || '/';
          if (url.includes('/passport')) url = '/';
          this.router.navigateByUrl(url, {
            replaceUrl: true
          });
        });
      });
  }


  ngOnDestroy(): void {
    if (this.interval$) clearInterval(this.interval$);
  }

  ngOnInit(): void {
    this.form = this.fb.group({
      userName: [null, [Validators.required, Validators.minLength(4)]],
      password: [null, Validators.required],
      // mobile: [null, [Validators.required, Validators.pattern(/^1\d{10}$/)]],
      // captcha: [null, [Validators.required]],
      remember: [false],
    });
    this.rememberInit();
  }

  private rememberInit() {
    if (!this.form)
      return;
    var data = this.cacheSer.get('$remember', {mode: 'none'});
    if (data) {
      if (data.password) {
        this.autopwd = true;
        this.form.controls.password.setValue(data.password);
      }
      data.username && this.form.controls.userName.setValue(data.username);
      data.rememberme && this.form.controls.remember.setValue(data.rememberme);
    }
  }

  ngAfterViewInit(): void {
    this.modalSrv.closeAll();
  }
}
